package com.goods.shop.util;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class WeiXinResourceUtils {
    public static String fileMaterial(String url, File file,String name)throws Exception
    {
        String result=null;
        URL urlObj=new URL(url);
        HttpURLConnection con= (HttpURLConnection) urlObj.openConnection();
        con.setDoInput(true);
        con.setDoOutput(true);
        con.setUseCaches(false);//post方式不能用缓存
        con.setRequestProperty("Connection","Keep-Alive");
        con.setRequestProperty("Charset","UTF-8");
        //边界
        String BOUNDARY="--------------------"+System.currentTimeMillis();//TODO
        con.setRequestProperty("Content-Type","multipart/form-data;boundary="+BOUNDARY);
        //请求正文信息
        //第一部分
        StringBuilder builder=new StringBuilder("");
        builder.append("--");//必须多两道线
        builder.append(BOUNDARY);
        builder.append("\r\n");
        builder.append("Content-Disposition: form-data;name=\""+name+"\";filelength=\"" + file.length() + "\";filename=\""
                + file.getName() + "\"\r\n");
        builder.append("Content-Type:application/octet-stream\r\n\r\n");
        byte[] head=builder.toString().getBytes("utf-8");
        //获取输出流
        OutputStream out=new DataOutputStream(con.getOutputStream());
        //输出表头
        out.write(head);

        //正文部分
        //把文件以流文件的方式写到URL中
        DataInputStream in=new DataInputStream(new FileInputStream(file));
        int bytes=0;
        byte[] bufferOut=new byte[1024];
        while((bytes=in.read(bufferOut))!=-1){
            out.write(bufferOut,0,bytes);
        }
        in.close();

        //结尾部分
        byte[] foot=("\r\n--"+BOUNDARY+"--\r\n").getBytes("utf-8");
        out.write(foot);
        out.flush();
        out.close();
        StringBuilder resultBuilder=new StringBuilder();
        BufferedReader reader=new BufferedReader(new InputStreamReader(con.getInputStream()));
        String line=null;
        while((line=reader.readLine())!=null){
            resultBuilder.append(line);
        }

        if(result==null){
            result=resultBuilder.toString();
        }
        reader.close();
        return result;
    }
}
